package com.example.online_forum.controller;

import com.example.online_forum.common.AppResult;
import com.example.online_forum.common.ResultCode;
import com.example.online_forum.config.AppConfig;
import com.example.online_forum.model.Message;
import com.example.online_forum.model.User;
import com.example.online_forum.services.IMessageService;
import com.example.online_forum.services.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Api(tags = "消息接口")
@Slf4j
@RestController
@RequestMapping("/message")

public class MessageController {
    @Autowired
    IUserService userService;
    @Autowired
    IMessageService messageService;
    @ApiOperation("发送信息")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @ApiParam("接收者id") @RequestParam("receiveUserId") @NonNull Long receiveUserId,
                          @ApiParam("消息正文") @RequestParam("content") @NonNull String content){
        //1.当前用户的状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);

        }
        if(user.getState() == 1){
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        if(receiveUserId == user.getId()){
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed("不能给自己发送站内信");
        }
        //校验接收者是否存在
        User receiveUser = userService.selectById(receiveUserId);
        if(receiveUser == null || receiveUser.getDeleteState() == 1){
            return AppResult.failed("接收者状态异常");
        }
        //封装对象
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(receiveUser.getId());
        message.setReceiveUserId(receiveUserId);
        message.setContent(content);
        //调用service
        messageService.create(message);
        //返回结果
        return AppResult.success("发送成功");
    }
    @ApiOperation("获取未读数量")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request){
        //获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //调用服务层
        //接收者id
        Integer count = messageService.selectUnreadCount(user.getId());
        //返回结果
        return AppResult.success(count);
    }
    @ApiOperation("获取用户所有的站内信")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request){
        //调用当前登录的用户
       HttpSession session =  request.getSession(false);
       User user  = (User) session.getAttribute(AppConfig.USER_SESSION);
       List<Message> messages = messageService.selectByReceiveUserId(user.getId());
       return AppResult.success(messages);
     }

    /**
     * 更新站内信为已读状态
     * @param id
     * @return
     */
     @ApiOperation("更新消息为已读状态")
     @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,@ApiParam("站内信id") @RequestParam("id") @NonNull Long id){
        //参数校验
         //根据id查询消息信息
         Message message = messageService.selectById(id);
         //消息是否存在
         if(message == null || message.getDeleteState() == 1 ){
             log.warn(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());
             return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
         }
         //校验站内信是否是自己发送
         HttpSession session = request.getSession(false);
         User user = (User) session.getAttribute(AppConfig.USER_SESSION);
         if(user.getId() != message.getReceiveUserId()){
             //log.warn(ResultCode.FAILED_UNAUTHORIZED.toString());
             return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
         }
         //将站内信状态更新为已读
         messageService.updateStateById(id,(byte) 1);
        return AppResult.success();
     }
    @ApiOperation("回复站内信")
    @PostMapping("/reply")
    public AppResult reply (HttpServletRequest request,
                            @ApiParam("要回复的站内信Id") @RequestParam("repliedId") @NonNull Long repliedId,
                            @ApiParam("站内信的内容") @RequestParam("content") @NonNull String content) {
        // 校验当前登录用户的状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        // 校验要回复的站内信状态
        Message existsMessage = messageService.selectById(repliedId);
        if (existsMessage == null || existsMessage.getDeleteState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        // 不能给自己回复
        if (user.getId() == existsMessage.getPostUserId()) {
            // 返回错误描述
            return AppResult.failed("不能回复自己的站内信");
        }
        // 构造对象
        Message message = new Message();
        message.setPostUserId(user.getId()); // 发送者
        message.setReceiveUserId(existsMessage.getPostUserId()); // 接收者
        message.setContent(content); // 内容
        // 调用Service
        messageService.reply(repliedId, message);
        // 返回结果
        return AppResult.success();
    }

}
